import React, { useContext, useEffect, useMemo, useRef, useState } from 'react'
import { Button, DatePicker, Form, Select, Spin, Tooltip, message } from 'antd';
import classNames from 'classnames';
import moment from 'moment';
import { useMount } from 'react-use';

import BizIcon from '@/components/BizIcon';
import { SearchInput } from '@/components/UserForm';
import OrganizationSelect from '@/components/OrganizationSelect';
import { isSuccess } from '@/utils/request';
import If from '@/components/If';

import Search from '@/pages/SalaryManage/components/SuperSearch';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import { queryEmployeeList } from '@/services/salaryManage/salaryCommon';
import { fetchOrganizationListAndDefault } from '@/pages/SalaryManage/utils';
import {
    feedbackAssignTypeEnum,
    feedbackHandleEnum,
    feedbackHandleStatus,
    feedbackProblemTypeEnum,
    feedbackReceiveEnum
} from '@/pages/SalaryManage/enum';
import AutoDivider from '@/pages/SalaryManage/components/AutoDivider';
import { feedbackAll, queryDateRange, queryIsFeedbackMaster } from '@/services/salaryManage/salaryConfirm';
import { commonColumn, dateColumn, datetimeColumn } from '@/pages/SalaryManage/utils/TableUtil';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import EmployeeNameWrapper from '@/pages/SalaryManage/components/EmployeeNameWrapper';
import { TabStoreContext } from '@/pages/SalaryManage/constant/TabStoreContext';
import useFetchCountInfo from '@/pages/SalaryManage/SalaryConfirm/SalaryFeedback/hooks/useFetchCountInfo';

import useTableWrapper from './hooks/useTableWrapper';
import useSpecialCheck from './hooks/useSpecialCheck';
import useBatchAssign from './hooks/useBatchAssign';
import useAssignType from './hooks/useAssignType';
import useAssign from './hooks/useAssign';
import useTransfer from './hooks/useTransfer';

const { MonthPicker, RangePicker } = DatePicker;
const { Option } = Select;

const feedbackReceiveList = feedbackReceiveEnum.list();
const feedbackHandleList = feedbackHandleEnum.list();
const SearchWrapper = React.forwardRef(
    (
        {
            form,
            onShowBatchAssign,
            onShowAssignType,
            onSearch,
            monthRange,
            model,
            isMaster,
            organizationList
        },
        ref
    ) => {
        const { store: { organizationCode }, mergeTabStore } = useContext(TabStoreContext);
        const { getFieldDecorator } = form;

        ref(form);

        const disabledDate = current => {
            if (current && monthRange?.length) {
                return monthRange.indexOf(current.startOf('month').format('YYYY-MM-DD')) === -1;
            }
            if (!monthRange?.length) {
                return true;
            }
            return !monthRange;
        };

        const onChangeMonth = (date, dateString) => {
            mergeTabStore({
                period: dateString
            });
        };

        const handleOrganizationChange = value => {
            form.setFieldsValue({
                employeeCode: undefined,
                receiver: undefined,
                v_salaryDate: undefined
            });
            mergeTabStore({
                period: undefined,
                organizationCode: value
            });
        };

        return (
            <div>
                <Search.Wrapper onSearch={onSearch}>
                    <TwoColHead
                        left={
                            <Search.Commonly>
                                <Search.Item label="行政机构">
                                    {getFieldDecorator('organizationCode', {
                                        initialValue: organizationCode
                                    })(
                                        <OrganizationSelect
                                            isStrictly
                                            isNeedPermission
                                            style={{ width: 220 }}
                                            treeDataFromProp
                                            treeDataList={organizationList}
                                            onChange={handleOrganizationChange}
                                            allowClear={false}
                                        />
                                    )}
                                </Search.Item>
                                <Search.Item label="月份">
                                    {getFieldDecorator('v_salaryDate', {
                                        initialValue: model?.v_salaryDate
                                    })(<MonthPicker disabledDate={disabledDate} onChange={onChangeMonth} />)}
                                </Search.Item>
                            </Search.Commonly>
                        }
                        right={
                            <TwoColHead
                                left={
                                    isMaster ? (
                                        <Button type="primary" onClick={onShowBatchAssign}>
                                            批量分配
                                        </Button>
                                    ) : null
                                }
                                right={
                                    <AutoDivider>
                                        <If condition={isMaster}>
                                            <Tooltip title="设置分配方式">
                                                <Button className={salaryStyle.iconBtn} onClick={onShowAssignType}>
                                                    <BizIcon type="shezhi" className={salaryStyle.iconfont22} />
                                                </Button>
                                            </Tooltip>
                                        </If>
                                        {/*
                                        <Tooltip title="自定义表头">
                                            <BizIcon
                                                type="searchbar_modifyheader_icon_default"
                                                className={salaryStyle.iconfont22}
                                            />
                                        </Tooltip>
                                        */}
                                    </AutoDivider>
                                }
                                addMarginAtOuter={false}
                                addMarginInRightChild={false}
                                style={{ flex: 1 }}
                            />
                        }
                        addMarginInRightChild={false}
                    />

                    <Search.More>
                        <Search.Item label="提交时间">
                            {getFieldDecorator('v_submitTime')(<RangePicker style={{ width: '12.875em' }} />)}
                        </Search.Item>
                        <Search.Item label="提交人">
                            <span>
                                {getFieldDecorator('employeeCode')(
                                    <SearchInput
                                        params={{
                                            organizationCode: form?.getFieldValue('organizationCode')
                                        }}
                                        getData={async params => {
                                            if (!params.organizationCode) {
                                                return [];
                                            }
                                            const employeeResponse = await queryEmployeeList({
                                                organizationCode: params.organizationCode
                                            });
                                            return isSuccess(employeeResponse) ? employeeResponse.data || [] : [];
                                        }}
                                        selectProps={{
                                            placeholder: '请输入员工姓名',
                                            allowClear: true
                                        }}
                                        fieldsName={{
                                            value: 'employeeCode',
                                            title: 'name'
                                        }}
                                        style={{ width: '12.875em' }}
                                    />
                                )}
                            </span>
                        </Search.Item>

                        <Search.Item label="接收人">
                            <span>
                                {getFieldDecorator('receiver')(
                                    <SearchInput
                                        params={{
                                            organizationCode: form?.getFieldValue('organizationCode')
                                        }}
                                        getData={async params => {
                                            if (!params.organizationCode) {
                                                return [];
                                            }
                                            const employeeResponse = await queryEmployeeList({
                                                organizationCode: params.organizationCode
                                            });
                                            return isSuccess(employeeResponse) ? employeeResponse.data || [] : [];
                                        }}
                                        selectProps={{
                                            placeholder: '请输入员工姓名',
                                            allowClear: true
                                        }}
                                        fieldsName={{
                                            value: 'employeeCode',
                                            title: 'name'
                                        }}
                                        style={{ width: '12.875em' }}
                                    />
                                )}
                            </span>
                        </Search.Item>

                        <Search.Item label="接收状态">
                            {getFieldDecorator('receiveStatus', {
                                initialValue: null
                            })(
                                <Select>
                                    <Option value={null}>全部</Option>
                                    {feedbackReceiveList.map(item => (
                                        <Option key={item.value} value={item.value}>
                                            {feedbackReceiveEnum.getShowName(item.value)}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Search.Item>

                        <Search.Item label="处理状态">
                            {getFieldDecorator('status', {
                                initialValue: null
                            })(
                                <Select>
                                    <Option value={null}>全部</Option>
                                    {feedbackHandleList.map(item => (
                                        <Option key={item.value} value={item.value}>
                                            {feedbackHandleEnum.getShowName(item.value)}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Search.Item>
                    </Search.More>
                </Search.Wrapper>
            </div>
        );
    }
);

const checkableFn = record => !record?.receiver && record.status !== feedbackHandleStatus.HANDLED;
const tableColumns = ({ operateConfig }) => {
    const { specialCheckHook } = operateConfig;
    const { allCheckableRows /* selectedRows, */, CheckBoxTitle, CheckboxCell } = specialCheckHook;

    let result = [];

    // if (allCheckableRows && allCheckableRows.length > 0) {
    result.push({
        title: () => <CheckBoxTitle disabled={!allCheckableRows || allCheckableRows.length === 0} />,

        dataIndex: 'v_check',
        fixed: 'left',
        width: 40,
        render(text, record) {
            const checkable = checkableFn(record);

            return (
                <>
                    <CheckboxCell
                        record={record}
                        // style={{ visibility: !checkable ? 'hidden' : 'visible' }}
                        disabled={!checkable}
                    />
                </>
            );
        }
    });
    // }
    result = result.concat([
        {
            title: () => (
                <EmployeeNameWrapper
                    left={
                        <span
                            className={classNames(salaryStyle.circle)}
                            style={{ visibility: 'hidden' }}
                        />
                    }
                    name="姓名"
                />
            ),
            dataIndex: 'employeeName',
            fixed: 'left',
            width: 146,
            render(text, record) {
                const checkable = checkableFn(record);

                return (
                    <EmployeeNameWrapper
                        left={
                            <span
                                className={classNames(salaryStyle.circle)}
                                style={{ visibility: !checkable ? 'hidden' : 'visible' }}
                            />
                        }
                        name={<span title={text}><EmptyPlaceHolder value={text} /></span>}
                    />
                );
            }
        },
        commonColumn({
            title: '工号',
            dataIndex: 'employeeNo',
            fixed: 'left',
            width: 120
        }),
        commonColumn({
            title: '组织机构',
            dataIndex: 'departmentName',
            width: 220
        }),
        dateColumn(
            {
                title: '薪资月份',
                dataIndex: 'salaryDate',
                width: 95
            },
            { pattern: 'YYYY-MM' }
        ),
        datetimeColumn({
            title: '提交时间',
            dataIndex: 'submitTime',
            width: 180
        }),
        commonColumn({
            title: '反馈编号',
            dataIndex: 'feedbackNo',
            width: 120
        }),
        {
            title: '反馈内容',
            dataIndex: 'feedback',
            width: 250,
            render(text) {
                return (
                    <pre
                        style={{
                            marginBottom: 0,
                            display: 'inline-block',
                            whiteSpace: 'break-spaces',
                            wordBreak: 'break-all'
                        }}
                    >
                        <EmptyPlaceHolder value={text} />
                    </pre>
                );
            }
        },
        commonColumn({
            title: '接收人',
            dataIndex: 'receiver',
            width: 132
        }),
        {
            title: '接收状态',
            dataIndex: 'receiveStatus',
            width: 80,
            render(text) {
                return <EmptyPlaceHolder value={feedbackReceiveEnum.getShowName(text)} />;
            }
        },
        {
            title: '原因',
            dataIndex: 'reason',
            width: 120,
            render(text) {
                return (
                    <pre
                        style={{
                            marginBottom: 0,
                            display: 'inline-block',
                            whiteSpace: 'break-spaces',
                            wordBreak: 'break-all'
                        }}
                    >
                        <EmptyPlaceHolder value={text} />
                    </pre>
                );
            }
        },
        {
            title: '处理状态',
            dataIndex: 'status',
            width: 80,
            render(text) {
                return <EmptyPlaceHolder value={feedbackHandleEnum.getShowName(text)} />;
            }
        },
        {
            title: '问题类型',
            dataIndex: 'problemType',
            width: 100,
            render(text) {
                return <EmptyPlaceHolder value={feedbackProblemTypeEnum.getShowName(text)} />;
            }
        },
        commonColumn({
            title: '解决时间',
            dataIndex: 'resolveTime',
            width: 180
        }),
        commonColumn({
            title: '耗时',
            dataIndex: 'timeConsuming',
            width: 100
        }),
        commonColumn({
            title: '处理结果',
            dataIndex: 'respondContent',
            width: 200,
            render(text) {
                return (
                    <pre
                        style={{
                            marginBottom: 0,
                            display: 'inline-block',
                            whiteSpace: 'break-spaces',
                            wordBreak: 'break-all'
                        }}
                    >
                        <EmptyPlaceHolder value={text} />
                    </pre>
                );
            }
        }),
        {
            title: '分配方式',
            dataIndex: 'assignType',
            width: 100,
            render(text) {
                return <EmptyPlaceHolder value={feedbackAssignTypeEnum.getShowName(text)} />;
            }
        },
        {
            title: '操作',
            dataIndex: 'v_operate',
            fixed: 'right',
            width: 80,
            align: 'center',
            render(text, record) {
                const { onShowAssign, onShowTransfer, isMaster } = operateConfig;

                return (
                    <AutoDivider>
                        {/* 接收人为空时，操作ICON显示为分配 */}
                        <If condition={isMaster && !record.receiver && record.status !== feedbackHandleStatus.HANDLED}>
                            <Tooltip title="分配">
                                <Button className={salaryStyle.operateIcon} onClick={() => onShowAssign(record)}>
                                    <BizIcon type="iconlistfunction_out" />
                                </Button>
                            </Tooltip>
                        </If>
                        {/* 存在接收人，但处理状态为未处理时显示为转配 */}
                        <If condition={isMaster && record.receiver && record.status === feedbackHandleStatus.HANDLING}>
                            <Tooltip title="转配">
                                <Button className={salaryStyle.operateIcon} onClick={() => onShowTransfer(record)}>
                                    <BizIcon type="zhidingfuzeren1" />
                                </Button>
                            </Tooltip>
                        </If>
                    </AutoDivider>
                );
            }
        }
    ]);

    return result;
};

const All = () => {
    const { store: { organizationCode, period }, mergeTabStore } = useContext(TabStoreContext);

    const [pageLoading, setPageLoading] = useState(false);
    const { dataSource, pagination, setDataSource, setPagination, render: TableWrapper } = useTableWrapper();
    // 当前操作行数据
    const [operateRecord, setOperateRecord] = useState(null);
    const [monthRange, setMonthRange] = useState([]);
    const [isMaster, setIsMaster] = useState(false);
    const [organizationTreeData, setOrganizationTreeData] = useState({});
    const [selectOrganizationCode, setSelectOrganizationCode] = useState(null);
    // 获取页签统计个数
    const fetchCountInfo = useFetchCountInfo();
    const searchForm = useRef();

    const getSearchCondition = () => searchForm.current?.getFieldsValue();
    // 获取查询条件
    const getPostData = searchCondition => {
        const { v_salaryDate, v_submitTime, ...postData } = searchCondition;

        if (v_salaryDate) {
            postData.salaryDate = v_salaryDate?.startOf('month')?.format('YYYY-MM-DD');
        }

        if (v_submitTime && v_submitTime.length > 0) {
            postData.submitStartTime = v_submitTime[0].startOf('day').format('YYYY-MM-DD HH:mm:ss');
            postData.submitEndTime = v_submitTime[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
        }

        return {
            ...postData,
            pageNo: postData?.current || pagination.current || 1,
            pageSize: postData?.pageSize || pagination.pageSize || 10
        };
    };

    const search = searchCondition => {
        const preCondition = (!searchCondition || (searchCondition?.current || searchCondition?.pageSize))
            ? { organizationCode: selectOrganizationCode, ...getSearchCondition(), ...searchCondition || {} }
            : searchCondition;
        const postData = getPostData(preCondition);
        if (!organizationCode && postData.organizationCode) {
            mergeTabStore({
                organizationCode: postData.organizationCode
            });
        }
        setPageLoading(true);
        feedbackAll(postData)
            .then(searchResponse => {
                if (isSuccess(searchResponse)) {
                    const { pageSize, total, pageNo: current, rows } = searchResponse.data;
                    setDataSource(rows);
                    setPagination({
                        ...pagination,
                        pageSize: pageSize || 10,
                        current: current || 1,
                        total
                    });
                    fetchCountInfo({ organizationCode: postData.organizationCode });
                } else {
                    message.error(searchResponse.msg);
                }
            })
            .finally(() => setPageLoading(false));
    };

    const specialCheckHook = useSpecialCheck(dataSource, checkableFn);
    const { selectedRows } = specialCheckHook;
    const { onShowBatchAssign, render: renderBatchAssignModal } = useBatchAssign(
        organizationCode,
        search,
        selectedRows
    );
    const { onShowAssignType, render: renderAssignTypeModal } = useAssignType(organizationCode, search);
    const { onShowAssign, render: renderAssignModal } = useAssign(
        organizationCode,
        operateRecord,
        setOperateRecord,
        search
    );
    const { onShowTransfer, render: renderTransferModal } = useTransfer(
        organizationCode,
        operateRecord,
        setOperateRecord,
        search
    );

    const EnhancedSearchWrapper = useMemo(
        () =>
            Form.create({
                /* 不立即搜索
            onValuesChange: (props, changedValues, allValues) => {
                 search(allValues);
            }
            */
            })(SearchWrapper),
        []
    );

    useEffect(() => {
        const requestOrganizationCode = selectOrganizationCode;

        if (requestOrganizationCode) {
            queryDateRange({ organizationCode: requestOrganizationCode }).then(response => {
                if (isSuccess(response)) {
                    const range = response.data;
                    setMonthRange(range && range.length > 0 ? range : []);
                } else {
                    message.error(response.msg);
                }
            });
        }
    }, [selectOrganizationCode]);

    useEffect(() => {
        const requestOrganizationCode = selectOrganizationCode;

        if (requestOrganizationCode) {
            queryIsFeedbackMaster({ organizationCode: requestOrganizationCode }).then(response => {
                if (isSuccess(response)) {
                    setIsMaster(response.data);
                } else {
                    message.error(response.msg);
                }
            });
        }
    }, [selectOrganizationCode]);

    useEffect(() => {
        setSelectOrganizationCode(organizationCode);
    }, [organizationCode]);

    useMount(() => {
        fetchOrganizationListAndDefault(organizationCode).then(
            ({ organizationResponse, defaultOrganizationCode: defaultSelectCode }) => {
                setOrganizationTreeData(organizationResponse);
                setSelectOrganizationCode(defaultSelectCode);

                const condition = getPostData({
                    ...getSearchCondition(),
                    organizationCode: defaultSelectCode,
                    v_salaryDate: period ? moment(period, 'YYYY-MM-DD') : null
                });
                if (defaultSelectCode) {
                    search(condition);
                }
            }
        );
    });

    const salaryDate = period ? moment(period, 'YYYY-MM-DD') : null;

    return (
        <Spin spinning={pageLoading}>
            <EnhancedSearchWrapper
                monthRange={monthRange}
                onShowBatchAssign={onShowBatchAssign}
                onShowAssignType={onShowAssignType}
                onSearch={search}
                wrappedComponentRef={form => {
                    searchForm.current = form;
                }}
                model={{
                    v_salaryDate: salaryDate
                }}
                isMaster={isMaster}
                organizationCode={selectOrganizationCode}
                organizationList={organizationTreeData}
            />
            <TableWrapper
                columns={tableColumns({
                    operateConfig: {
                        specialCheckHook,
                        onShowAssign,
                        onShowTransfer,
                        isMaster
                    }
                })}
                search={search}
            />
            {renderBatchAssignModal()}
            {renderAssignTypeModal()}
            {renderAssignModal()}
            {renderTransferModal()}
        </Spin>
    );
};

export default React.memo(All);
